package cn.itcast.bos.web.action;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.persistence.Access;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.omg.CORBA.PRIVATE_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.Utils.MailUtils;
import cn.itcast.bos.domain.constant.Constants;
import cn.itcast.crm.domain.Customer;
import oracle.net.aso.a;

@SuppressWarnings("serial")
@Namespace("/")
@ParentPackage("json-default")
@Controller
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer> {
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;

	@Action(value = "customer_sendSms")
	public String sendSms() throws Exception {
		String randomCode = RandomStringUtils.randomNumeric(4);
		// 将短信验证码保存到 session里面
		ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), randomCode);
		System.out.println("生成手机验证码是" + randomCode);

		// 编辑短信内容   短信生产者
		@SuppressWarnings("unused")
		final String msgContent = "尊敬的用户您好,本次获取的验证码为:" + randomCode + ",服务电话,400-80001324";

		// 调用mq发送信息 2. 在CustomerActive中，属性注入JmsTemplate模板，
		// 在调用jmsTemplate的send方法来发 生产消息，注意，因为这里的消息中因为要有两个内容，
		// 手机号码和短信验证码，所以不 能用textMessage文本消息，而要用mapMessage
		jmsTemplate.send("bos_sendMessage", new MessageCreator() {

			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", model.getTelephone());
				mapMessage.setString("msgContent", msgContent);
				return mapMessage;
			}
		});

		return NONE;


	}

	// 属性驱动
	private String checkcode;

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	// 属性注入RedisTemplate 把下面的激活码存入到Redis内存数据库中
	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	// 用户注册 注册成功 跳到注册成功页面 注册失败返回原注册页面
	@Action(value = "customer_regist", results = {
			@Result(name = "success", type = "redirect", location = "signup-success.html"),
			@Result(name = "input", type = "redirect", location = "signup.html") })
	public String regiest() {
		// 验证短信码 不通过 回到注册页面
		// 上述短信发送时生成的短信验证码保存在session中 现在将session中获取的验证码和前台提交的验证做比较 从
		String sessionCheckCode = (String) ServletActionContext.getRequest().getSession()
				.getAttribute(model.getTelephone());
		// 如果session中的验证码为空 或者不一致 短信验证码错误
		if (sessionCheckCode == null || !sessionCheckCode.equals(checkcode)) {
			System.out.println("短信验证码错误" + sessionCheckCode);
			return INPUT;
		}
		// 调用webService 连接crm 保存客户信息 发送端
		WebClient.create("http://localhost:9002/crm_management/services/customerService/registCustomer")
				.type(MediaType.APPLICATION_JSON).post(model);
		System.out.println("客户注册成功");

		// 给客户发送邮件 并将邮件中的激活码和账号(即使手机号码) 存入Redis中 设置为24小时失效
		// 1.生成激活码
		String activeCode = RandomStringUtils.randomNumeric(10);
		System.out.println("jihu激活码"+activeCode);
		// 2.将激活码把偶才能到Redis中
		redisTemplate.opsForValue().set(model.getTelephone(), activeCode, 24, TimeUnit.HOURS);
		System.out.println("redis激活码"+activeCode);
		// 3 发送邮件
		String content = "尊敬的用户您好，请于24小时内，进行邮箱账户的绑定，点击下面地址完成绑定：<br />" + "<a href='" + MailUtils.activeUrl
				+ "?telephone=" + model.getTelephone() + "&activecode=" + activeCode + "'>" + "速快递邮箱绑定地址</a> ";
		MailUtils.sendMail("速运快递激活邮件", content, model.getEmail());
		return SUCCESS;
	}

	private String activecode;

	public void setActivecode(String activecode) {
		this.activecode = activecode;
	}

	@Action("customer_activeMail") // customer_activeMail 是activeUrl 里面请求路径
									// 在MailUtils里面 return返回none 代表这个方法不需要进行任何操作
	public String activeMail() throws IOException {
		ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
		// 1.取出Redis中的激活码
		String redisactiveCode = redisTemplate.opsForValue().get(model.getTelephone());
		System.out.println("取出的激活码是" + redisactiveCode);
		System.out.println("前台传过来的激活码是"+activecode);
		// 2.校验激活码是否激活
		if (redisactiveCode == null || !redisactiveCode.equals(activecode)) {
			// 无效的激活码
			ServletActionContext.getResponse().getWriter().println("激活码无效,请登录系统，重新绑定邮箱");
		} else {
			// 激活码有效 根据手机调用webService查询客户对象 判断客户是否激活 避免重复点击
			Customer customer = WebClient
					.create("http://localhost:9002/crm_management/services/customerService/customer/telephone/"
							+ model.getTelephone())
					.accept(MediaType.APPLICATION_JSON).get(Customer.class); // 指的是我要返回一个Customer对象
			// 判断是否激活
			if (customer.getType() == null || customer.getType() != 1) {
				// 如果未激活 调用webService修改客户type为1 为激活
				WebClient.create("http://localhost:9002/crm_management/services/customerService/customer/updatetype/"
						+ model.getTelephone()).get();
				ServletActionContext.getResponse().getWriter().println("邮箱绑定成功");
			} else {
				// 已激活 给出提示
				ServletActionContext.getResponse().getWriter().println("邮箱已经绑定过，无须重复绑定");
			}
			// 删除Redis的激活码
			redisTemplate.delete(model.getTelephone());
		}
		return NONE;
	}
	
	
	
	
	
	//客户登录功能
	@Action(value="customer_login",results={@Result(name="login",location="login.html",type="redirect"),
			@Result(name="success",location="index.html#/myhome",type="redirect")})
	public String login(){
		//调用webService去crm_management系统查询 改账号和密码是否存在
//		Customer customer = WebClient.create(Constants.CRM_MANAGEMENT_URL+
//				"/services/customerSerivce/customer/login?telephone="+model.getTelephone()+"&password="+
//				model.getPassword()).accept(MediaType.APPLICATION_JSON).get(Customer.class);
		Customer customer = WebClient
				.create(Constants.CRM_MANAGEMENT_URL
						+ "/services/customerService/customer/login?telephone="
						+ model.getTelephone() + "&password="
						+ model.getPassword()).accept(MediaType.APPLICATION_JSON).get(Customer.class);
		//判断输入的用户名是否通过
		if(customer == null){
			return LOGIN;
		}else{
			ServletActionContext.getRequest().getSession().setAttribute("customer", customer);
			System.out.println("手机号和密码"+model.getTelephone()+model.getPassword());
			return SUCCESS;
		}
		
	}
}
